﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Fills isolated interior pixels (individual 0s that are surrounded by 1s), such as the center pixel in this pattern.
    /// 1  1  1 
    /// 1  0  1 
    /// 1  1  1
    /// </summary>
    public class Fill : BaseForeBackgroundColorFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Fill"/> class.
        /// </summary>
        public Fill()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Fill"/> class.
        /// </summary>
        /// <param name="_fill">The _fill.</param>
        internal Fill(Fill _fill)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int y = 0;
            int x = 0;
            int nHeight = _bitmap.Height;
            int nWidth = _bitmap.Width;

            Color[] aColor = new Color[8];

            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();

            int nForegroundCount = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    aColor = Segmentation.GetEnvironmentPixelColorArray(bitmapCloned, x, y, Definitions.EnvironmentPointListClockwise, aColor);

                    nForegroundCount = 0;

                    foreach (Color colorEnvironment in aColor)
                    {
                        if (colorEnvironment == m_ColorForeground)
                        {
                            nForegroundCount++;
                        }
                    }
                    if (_bitmap.GetPixel(x, y) == m_ColorBackground && nForegroundCount == 8)
                    {
                        _bitmap.SetPixel(x, y, m_ColorForeground);
                    }
                }
            }
            bitmapCloned.Dispose();
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new Fill(this);
        }
    }
}
